import time
import xlwt
import requests
from lxml import etree

t=time.time()-604800#计算七天前的时间戳
today=time.localtime()#获取今天的日期
ago=time.localtime(t)#获取七天前的日期

today_m=int(today.tm_mon)
today_d=int(today.tm_mday)
ago_m=int(ago.tm_mon)
ago_d=int(ago.tm_mday)


headers={'User-Agent':"Mozilla/5.0 (Windows NT 10.0; Win32; x32) AppleWebKit/537.33 (KHTML, like Gecko) Chrome/107.0.5241.132 Safari/537.36 Edg/103.0.1754.31"}
text_list=[]#用来收集评论
time_list=[]#用来收集时间

list_number=['300269','688496','873001','300323','300812','831167','002660','002655','000625','002594','601127','000951','300364','002517','600228','603466','603716','603108','301408','600829']
list_title=['联建光电','清越科技','纬达光电','华灿光电','易天股份','鑫汇科','茂硕电源','共达电声','长安汽车','比亚迪','赛力斯','中国重汽','中文在线','恺英网络','返利科技','风语筑','塞力医疗','润达医疗','华人健康','人民同泰']
url_list=[]
for s in list_number:
    url_list.append('https://guba.eastmoney.com/list,{},f.html'.format(s))
for k in range(0,20):#设置爬取股票的序号
    text_list=[]
    time_list=[]
    for i in range(1,200):#爬前200页,为了尽可能包括前七天的评论，这里的页数可以尽量大
        url=url_list[k].replace('.html','_{}.html'.format(i))#每次循环替换页码值
        response=requests.get(url=url, headers=headers)
        response.encoding='utf-8'
        maintree = etree.HTML(response.text)
        list1=maintree.xpath('//*[@id="mainlist"]/div/ul/li[1]/table/tbody/tr/td[3]/div/a//text()')#用xpath得到一页中所有评论
        list2=maintree.xpath('///*[@id="mainlist"]/div/ul/li[1]/table/tbody/tr/td[5]/div//text()')#用xpath得到一页中所有时间
        time1 = int(list2[0][3:5])#日
        time2 = int(list2[0][:2])#月
        if time2==ago_m and time1<ago_d: break#发现日期不对结束循环
        text_list=text_list+list1#合并评论列表
        time_list=time_list+list2#合并时间列表
        time.sleep(0.1)#防检测

    w=xlwt.Workbook()#写入excel表格
    s=w.add_sheet('s1')
    s.write(0,0,'评论')
    s.write(0,1,'时间')
    j=1
    for m in range(0,len(text_list)):
        time1=int(time_list[m][3:5])
        time2=int(time_list[m][:2])
        if (time2 == ago_m and time1 > ago_d) or (time2==today_m and time1<today_d):#只取前七天
            s.write(j,0,text_list[m])
            s.write(j,1,time_list[m])
            j=j+1
        else:
            continue
    s='data/{}.xls'.format(list_title[k])
    w.save(s)#存储到本地
    print('{}'.format(list_title[k])+'已完成')